# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import pymongo
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem


class LjPipeline:

    def __init__(self):
        self.client = None
        self.db = None

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(spider.settings["MONGO_HOST"])
        self.db = self.client[spider.settings["MONGO_DB"]]

    def process_item(self, item, spider):
        data = dict(item)
        if isinstance(data, dict):
            self.db["nj_lj"].insert_one(data)
            return item
        else:
            raise DropItem(f"数据格式错误-{item}")

    def close_spider(self, spider):
        if self.client is not None and self.db is not None:
            self.client.close()
            self.db.close()
